<template>
  <el-dialog v-model="show">
    <el-form :model="props.row" :rules="rules" label-width="120" ref="formRef">
      <el-form-item label="分类名称" prop="category_name">
        <el-input v-model="props.row.category_name"></el-input>
      </el-form-item>
      <el-form-item label="排序值">
        <el-input-number v-model="props.row.category_sort" :min="1" :max="100"></el-input-number>
      </el-form-item>
      <el-form-item label="是否自定义">
        <el-switch
          :inactive-value="false"
          :active-value="true"
          inactive-text="否"
          active-text="是"
          v-model="props.row.can_edit"
        ></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { FormInstance, FormRules } from "element-plus";
import { ref } from "vue";

interface Row {
  category_name: string;
  category_sort: number;
  can_edit: boolean;
}

interface Props {
  row: Row;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
}

const props = ref<Props>({
  row: { can_edit: false, category_name: "", category_sort: 100 }
});

const rules: FormRules = {
  category_name: [
    { required: true, message: "分类名称不可为空", trigger: "blur" },
    { max: 10, min: 1, message: "字数在1-10之间" }
  ]
};

const show = ref(false);

const open = (params: Props) => {
  show.value = true;
  props.value = params;
};

const formRef = ref<FormInstance>();
const confirm = () => {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await props.value.api!(props.value.row);
      await props.value.getTable!();
      show.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({ open });
</script>

<style></style>
